﻿using OU.SerialPort;
using OU.SerialPort.Com;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Threading;

namespace OU.OnlineUpdate
{

    public partial class MainWindow : Window
    {
        public IComLib _comLib;
        private DispatcherTimer _timer;

        public MainWindow()
        {
            _comLib = new ComLib();
            InitializeComponent();
            _comLib.MessageReceive += MessageReceive;
            _timer = new DispatcherTimer();
            _timer.Interval = TimeSpan.FromMilliseconds(60);
            _timer.Tick += Timer_Tick;
            _timer.Start();
            Run();
        }

        #region 自动检测串口
        /// <summary>
        /// 自动检测串口
        /// </summary>
        int times = 0;
        ushort index = 0;
        private void Timer_Tick(object? sender, EventArgs e)
        {
            times++;
            if (times / 50 == 1)
            {
                comlist.ItemsSource = PortSearch.SearchPort();
                times = 0;

            }
            if ((ComLib.serialPort != null) && ComLib.serialPort.IsConnected)
            {
                index++;
                if (index >= splitDictionary.Count()) index = 0;
                var data = splitDictionary[index];
                Data.SendDataInclueBit[14] = (byte)data.SplitLength;
                Data.SetSendHead(index, (ushort)splitDictionary.Count());
                for (int j = 0; j < data.SplitLength; j++)
                {
                    Data.SendDataInclueBit[j + 20] = (byte)data.Data[j];
                }
                _comLib.SendMessge(Data.SendDataInclueBit);
            }

        }
        #endregion

        #region ZTM
        //接收消息并展示
        private void MessageReceive(byte[] obj)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                showResult.Text = string.Join(" ", obj.Select(b => b.ToString("X2")));
            });
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            string comname = "";
            if (comlist.Text.Contains("("))
                comname = comlist.Text.Split('(')[1].Replace(")", "");
            if (comname.Contains("->"))
                comname = comname.Split('-')[0];
            connect.Content = _comLib.OpenCloseCom(comname);
        }

        private void cmdlist_Selected(object sender, RoutedEventArgs e)
        {
            //var dd = cmdlist.SelectedItem as EnumItem;
            //content.Text = string.Join(" ", dd.HexValue.Select(b => b.ToString("X2")));

        }

        private void TextBox_TextChanged(object sender, RoutedEventArgs e)
        {
            if (OFP.Content.ToString() == "OFP加载模式")
            {
                OFP.Content = "正常运行模式";
                Data.SendDataDefalut.SetBitInByteArray(60, 3, false);
                // Data.SendDataDefalut.SetBitInByteArray(61,0, false);
                Data.SendDataDefalut.SetBitInByteArray(61, 4, false);
            }
            else
            {
                OFP.Content = "OFP加载模式";
                Data.SendDataDefalut.SetBitInByteArray(60, 3, true);
                //Data.SendDataDefalut.SetBitInByteArray(61, 0, true);
                Data.SendDataDefalut.SetBitInByteArray(61, 4, true);
            }

        }
        #endregion

        #region ICountPD

        #endregion
        Dictionary<ushort, SplitData> splitDictionary;
        public void Run()
        {

            int file_len;//bin文件长度
            int addr = 0;//地址从0x00000000开始
            int count = 0;//换行显示计数
            byte[] binchar = new byte[] { };
            FileStream Myfile = new FileStream(@"C:\Users\guangbo\workspace_v12\QFXH-65\Release\QFXH62_01_315_M_V1.00.bin", FileMode.Open, FileAccess.Read);
            BinaryReader binreader = new BinaryReader(Myfile);

            file_len = (int)Myfile.Length;//获取bin文件长度

            StringBuilder str = new StringBuilder();

            binchar = binreader.ReadBytes(file_len);
            ushort splitLength = 64; // 假设每份的长度是1024字节  
            splitDictionary = new Dictionary<ushort, SplitData>();
            ushort key = 0;

            for (int i = 0; i < binchar.Length; i += splitLength)
            {
                int remainingLength = binchar.Length - i;
                int actualLength = Math.Min(splitLength, remainingLength);

                byte[] splitData = new byte[actualLength];
                Array.Copy(binchar, i, splitData, 0, actualLength);

                SplitData splitDataObj = new SplitData(Convert.ToUInt16(actualLength), splitData);
                splitDictionary.Add(key, splitDataObj);

                key++;
            }
            foreach (byte j in binchar)
            {
                if (count % 64 == 0)
                {
                    count = 0;
                    if (addr > 0)
                        str.Append("\r\n");
                    str.Append(addr.ToString("x8") + "      ");
                    addr++;
                }

                str.Append(j.ToString("X2") + " ");
                if (count == 8)
                    str.Append("  ");
                count++;
            }
            string dd = str.ToString();
            File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "1.txt", dd);
            binreader.Close();
        }

    }


}